package IntelSpam::Filters::OCRFilter;

use 1.0;

use strict;
use warnings;

use MIME::Parser;
use IntelSpam::Config;
use Data::Dumper;
use Image::Magick;
use Log::Log4perl qw(get_logger);

our $VERSION = '1.0';
our $DEBUG = 1;

our $REGISTER = ['body'];
our $META = {
	'id' => 'ocr_filter',
	'name' => 'Dummy Filter',
	'description' => 'OCR Filter for image attachments',
	'version' => '1.0',
	'weight' => 20
	
};

our $CFG = {};
our @bad_words = ();
our $TESSERACT = "tesseract";

our $logger = get_logger("IntelSpam::OCRFilter");

sub new($){
	bless {}, shift;
}

sub filter_body($$$){
	my ($this, $ctx, $entity) = @_;

	unless (-f $TESSERACT) { $logger->error("Could not found $TESSERACT, please install tesseract-ocr package."); return; }
	find_image_and_ocr($ctx, $entity);
}

sub find_image_and_ocr {
    my ($ctx, $entity, $name) = @_;
    defined($name) or $name = "'anonymous'";
    my $IO;


    # Output the body:
    my @parts = $entity->parts;
    if (@parts) {                     # multipart...
	my $i;
	foreach $i (0 .. $#parts) {       # dump each part...
	    find_image_and_ocr($ctx, $parts[$i], ("$name, part ".(1+$i)));
	}
    }
    else {                            # single part...	

	# Get MIME type, and display accordingly...
	my ($type, $subtype) = split('/', $entity->head->mime_type);
	my $body = $entity->bodyhandle;
	
	if ($type =~ /^(image)$/) {    
		my $path = $body->path;
		my ($result, $line);
		my $img = Image::Magick->new;
		$img->Read(filename => $path);
		$img->Write(filename => "$path.bmp", compression => 'None');
		$logger->info("OCR scanning..");
		system "tesseract", $path.".bmp", $path;
		open $result, "< $path.txt";
		my $contents;
		while($line = <$result>){
			$contents .= $line . '\n';
		}
		close($result);
		$logger->info("OCR scanning done.");
		$logger->debug("OCR result: $contents");
		my @words = split(/\s+/, $contents); 
		my $wc = $#words + 1;
		if($wc eq 0){
			$wc = 1;
		}
		
		
		my $score = 0;
		$_ = $contents;
		foreach my $bw (@bad_words) {
			chop $bw;
			my $occ=()=/$bw/gi;
			$score += $occ;
		}
		#print "($score/$wc) * " . $META->{'weight'};
		$score = ($score/$wc) * $META->{'weight'};
		if($score > 0){
			$score = $META->{'weight'} - $score;
		}
		$ctx->getpriv()->{'score'}->insert($META->{'id'}, $META->{'weight'}, $score);
	}
    }
    0;
}

sub get_registers($){
	$REGISTER;
}

sub get_meta($){
	$META;
}

sub set_cfg($$){
	my $this = shift;
	$CFG = shift;
	my $conf = $CFG->getcfg($META->{'id'});
	if(defined $conf->{'embed'} && $conf->{'embed'} eq 'true'){
		@bad_words = split(/\n/, $conf->{'badwords'});

	}else{
		open FILE, "<", $conf->{'badwords'} or die $!;
		while(<FILE>){
			chop $_;
			push @bad_words, $_;
		}
	}
	$logger->info("Loaded ". ($#bad_words + 1) ." badword(s)");

	$TESSERACT = $conf->{'tesseract_path'};
	close(FILE);
}

1;
